package com.chenliang.service.impl;

import com.chenliang.dao.IUsersInfo;
import com.chenliang.domain.Role;
import com.chenliang.domain.UserInfo;
import com.chenliang.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @ProjectName: mavenSSM
 * @Package: com.chenliang.service.impl
 * 作用：
 */
@Service("userService")
public class UserServiceImpl implements IUserService {
    @Autowired
    private IUsersInfo usersInfo;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        UserInfo userInfo = usersInfo.findByUsername(s);
        User user = null;

        try {
            user = new User(userInfo.getUsername(), userInfo.getPassword(), userInfo.getStatus() == 0 ? false : true, true, true, true, getAuthority(userInfo.getRoles()));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return user;
    }


//    定义一个方法，把定义的角色名进行拼接，给定权限
    private List<SimpleGrantedAuthority> getAuthority(List<Role> roles) {

        List<SimpleGrantedAuthority> authorityList = new ArrayList<SimpleGrantedAuthority>();
        for (Role role : roles) {
            authorityList.add(new SimpleGrantedAuthority("ROLE_" + role.getRoleName()));
        }
        return authorityList;
    }
}
